﻿using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;
using Wechat_PublicNumber.Common;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model;
using Wechat_PublicNumber.Model.Input;
using Wechat_PublicNumber.Model.Output;
using Wechat_PublicNumber.Repository;

namespace Wechat_PublicNumber.Controllers
{
    [Route("Stock")]
    [ApiController]
    public class StockController : BasicController
    {

        #region DI
        [Autowired]
        private StockRepository _stockRepository;

        [Autowired]
        private CommonHttpInvoke _commonHttpInvoke;
        #endregion

        /// <summary>
        /// 获取用户监听股票列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<GetStockListOutput> GetStockList([FromQuery] string KeyWord)
        {
            try
            {
                return new GetStockListOutput()
                {
                    List = await _stockRepository.GetUserStockList(UserInfo.OpenID, KeyWord),
                    Page = _page
                };
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "GetStockList Error");
                throw;
            }
        }

        /// <summary>
        /// 查询股票
        /// </summary>
        /// <param name="KeyWord">关键字</param>
        /// <returns></returns>
        [HttpGet("Search")]
        public async Task<List<SearchStockOutput>> SearchStock([FromQuery] string KeyWord)
        {
            try
            {
                List<SearchStockOutput> returnData = new List<SearchStockOutput>();

                if (string.IsNullOrEmpty(KeyWord))
                    return returnData;

                var stockList = await _commonHttpInvoke.GetStockInfo(KeyWord);
                if (stockList != null)
                {
                    returnData = stockList.Select(s => new SearchStockOutput
                    {
                        Code = s.code,
                        Name = s.query,
                    }).ToList();
                }
                return returnData;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "GetStockList Error");
                throw;
            }
        }

        /// <summary>
        /// 保存股票
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> SaveStock([FromBody] SaveStockInput input)
        {
            try
            {
                var now = DateTime.Now;
                string code = string.Empty;
                Regex regex = new Regex(@"\((SZ|SH)\d{6}\)");
                Match match = regex.Match(input.StockName);
                if (match.Success)
                    code = match.Value.Trim('(', ')');
                else
                    throw new OutPutException("不正确的股票名称");

                var stockInfo = (await _commonHttpInvoke.GetStockInfo(code)).FirstOrDefault();
                if (stockInfo == null)
                    throw new OutPutException("未找到该股票");

                var codeNumber = stockInfo.code.Substring(2, 6);

                UserStock userStock = null;
                var stock = await _stockRepository.GetStockByKeyword(codeNumber);
                if (stock == null)
                {
                    stock = new Stock()
                    {
                        BelongStockExchange = Enum.Parse<StockExchange>(stockInfo.code.Substring(0, 2)),
                        StockCode = codeNumber,
                        StockName = stockInfo.query,
                        CreateTime = now
                    };
                }

                var userNowStock = await _stockRepository.GetUserStockByOpenID(stock.ID, UserInfo.OpenID);
                if (userNowStock != null)
                {
                    var count = userNowStock.Count;
                    if (input.ID == 0)
                        count++;
                    else
                        count--;

                    if (count > 2)
                        throw new OutPutException("每个股票最多添加两条监听数据！！");
                }

                userStock = await _stockRepository.GetUserStockEntityByID(input.ID);
                if (userStock == null)
                {
                    userStock = new UserStock()
                    {
                        OpenID = UserInfo.OpenID,
                        CreateTime = now
                    };
                }
                else userStock.UpdateTime = now;

                userStock.RemindChg = input.RemindChg;
                userStock.RemindPercent = input.RemindPercent;
                userStock.RemindPrice = input.RemindPrice;

                await _stockRepository.SaveStock(stock, userStock);

                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "AddStock Error");
                throw;
            }
        }

        /// <summary>
        /// 删除股票
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        /// <exception cref="OutPutException"></exception>
        [HttpDelete("{ID}")]
        public async Task<bool> DeleteStock([FromRoute] long ID)
        {
            try
            {
                if (ID == 0) throw new OutPutException("ID不能为空");

                await _stockRepository.DeleteUserStock(ID);

                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "DeleteStock Error");
                throw;
            }
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        /// <exception cref="OutPutException"></exception>
        [HttpGet("{ID}")]
        public async Task<GetStockList> GetOneStock([FromRoute] long ID)
        {
            try
            {
                if (ID == 0) throw new OutPutException("ID不能为空");

                var returnData = await _stockRepository.GetUserStockByID(ID);
                if (returnData == null)
                    throw new OutPutException("数据不存在");

                return returnData;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "DeleteStock Error");
                throw;
            }
        }
    }
}
